<!doctype html>
<html lang="zh-cn">
<head>
  <meta charset="utf-8">
  <link rel="icon" href="favicon.ico" type="image/x-icon">
  <title>Python编程纠错助手</title>
  <link href="./assistant.css" rel="stylesheet">
  <link rel="stylesheet" href="./default.min.css">
  <script src="./marked.min.js"></script>
  <script src="./highlight.min.js"></script>
</head>
<body class="bg-gray-100 min-h-screen py-12 px-4 sm:px-6 lg:px-8">
    <div class="max-w-3xl mx-auto">
        <h1 class="text-3xl font-bold text-center text-gray-900 mb-8">Python编程纠错助手</h1>
        <div class="bg-white shadow-md rounded px-8 pt-6 pb-8 mb-4">
            <div class="mb-4">
                <label class="block text-gray-700 text-sm font-bold mb-2" for="pythonCode">
                    输入Python代码：
                </label>
                <textarea id="pythonCode" rows="10" class="shadow appearance-none border border-gray-500 rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline focus:border-gray-700" placeholder="在这里粘贴您的Python代码..."></textarea>
            </div>
            <div class="flex items-center justify-between">
                <button id="submitBtn" class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline" type="button">
                    分析代码
                </button>
            </div>
        </div>
        <div id="result" class="bg-white shadow-md rounded px-8 pt-6 pb-8 mb-4 hidden">
            <h2 class="text-xl font-bold text-gray-900 mb-4">分析结果：</h2>
            <div id="analysisResult" class="text-gray-700 prose"></div>
        </div>
    </div>

    <script>
        // 获取当前页面的文件名
        const currentPage = window.location.pathname.split('/').pop() || 'index.html';

        // 加载配置文件
        async function loadConfig() {
            try {
                const response = await fetch('config.json');
                const config = await response.json();
                return config;
            } catch (error) {
                console.error('Error loading config:', error);
                return null;
            }
        }

        document.addEventListener('DOMContentLoaded', async () => {
            const config = await loadConfig();
            if (!config) {
                console.error('Failed to load configuration');
                return;
            }

            // 获取当前页面的配置
            const pageConfig = config.page_config[currentPage];
            const apiConfig = config.api_config[pageConfig.default_api];

            // 初始化提示选择器（如果页面有多个可用提示）
            const promptSelector = document.getElementById('promptSelector');
            if (promptSelector && pageConfig.available_prompts) {
                // 清空现有选项
                promptSelector.innerHTML = '';
                
                // 添加可用的提示选项
                pageConfig.available_prompts.forEach(promptKey => {
                    const prompt = config.system_prompts[promptKey];
                    const option = document.createElement('option');
                    option.value = promptKey;
                    option.textContent = prompt.name;
                    if (promptKey === pageConfig.default_prompt) {
                        option.selected = true;
                    }
                    promptSelector.appendChild(option);
                });
            }

            document.getElementById('submitBtn').addEventListener('click', async () => {
                const pythonCode = document.getElementById('pythonCode').value;
                const resultDiv = document.getElementById('result');
                const analysisResultDiv = document.getElementById('analysisResult');

                // 显示加载中的消息
                resultDiv.classList.remove('hidden');
                analysisResultDiv.innerHTML = '正在分析代码，请稍候...';

                try {
                    // 获取当前选中的提示（如果有选择器）或使用默认提示
                    const selectedPrompt = promptSelector ? 
                        promptSelector.value : 
                        pageConfig.default_prompt;

                    const response = await fetch(apiConfig.url, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'Authorization': `Bearer ${apiConfig.api_key}`
                        },
                        body: JSON.stringify({
                            model: apiConfig.model,
                            messages: [
                                {
                                    role: "system",
                                    content: config.system_prompts[selectedPrompt].content
                                },
                                {
                                    role: "user",
                                    content: `请分析以下Python代码，指出错误并提供简单的解释：\n\n${pythonCode}`
                                }
                            ]
                        })
                    });

                    const data = await response.json();
                    const analysis = data.choices[0].message.content;

                    // 使用marked将Markdown转换为HTML
                    analysisResultDiv.innerHTML = marked.parse(analysis);

                    // 应用代码高亮
                    document.querySelectorAll('pre code').forEach((block) => {
                        hljs.highlightBlock(block);
                    });
                } catch (error) {
                    analysisResultDiv.innerHTML = '抱歉，分析过程中出现错误。请稍后再试。';
                    console.error('Error:', error);
                }
            });
        });
    </script>
</body>
</html>